package com.plz.afmt.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.google.common.collect.Lists;
import com.plz.afmt.enums.FileSuffixEnum;
import com.plz.afmt.service.OssService;
import com.plz.afmt.utils.NFileUtils;
import com.plz.common.exception.BusinessException;
import com.plz.shrio.annotation.IgnoreLogin;
import com.plz.web.base.controller.BaseController;
import com.plz.web.base.dto.Resp;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * @author jzc
 * 重写整理代码结构 by swing
 */
@Controller
@RequestMapping("/admin/file")
@Api(tags = "文件上传下载")
@ApiSort(20)
public class FileController extends BaseController {

    @Autowired
    private OssService ossService;

    @Value("${nos.oss.type:default:default}")
    private String ossType;
    @Value("${oss.upload.path:C:\\oss\\images}")
    private String uploadDir;

    /**
     * 本地上传的文件浏览器直接显示文件
     * attname 不为NULL则进行下载
     * @param name
     */

    @ApiOperationSupport(order = 1)
    @ApiOperation("文件显示")
    @GetMapping("/view/{name}")
    @IgnoreLogin
    @ResponseBody
    public void dw(@PathVariable("name") String name, @RequestParam(required = false) String attname) {
        File file = new File(getUploadDir(), name);
        OutputStream outputStream = null;
        if (file.exists() && file.isFile()) {
            try {
                HttpServletResponse response = getHttpServletResponse();
                response.reset();
                String fileType = name.substring(name.lastIndexOf('.') + 1);
                if (FileSuffixEnum.MP4.getValue().equals(fileType)) {
                    response.setHeader("Content-Disposition", "inline");
                    response.setContentType("video/mp4");
                }
                response.setContentType("application/octet-stream;charset=utf-8");
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.setCharacterEncoding("UTF-8");
                //开始下载
                if (StringUtils.isNotBlank(attname)) {
                    response.addHeader("Content-Disposition", "attachment;filename=" + new String(attname.getBytes("UTF-8"), "ISO-8859-1"));
                    response.addHeader("Content-Length", "" + file.length());
                }
                outputStream = response.getOutputStream();
                outputStream.write(FileUtils.readFileToByteArray(file));
                outputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 下载通用文件
     */
    @ApiOperationSupport(order = 2)
    @ApiOperation("文件下载")
    @GetMapping("df")
    @ResponseBody
    public void download(String name, @RequestParam(required = false) String newName, HttpServletResponse response) {
        File file = new File(getUploadDir(), name);
        OutputStream outputStream = null;
        if (file.exists()) {
            try {
                String filename = StringUtils.isNotBlank(newName) ? newName : file.getName();
                response.reset();
                response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes("UTF-8"), "ISO-8859-1"));
                response.addHeader("Content-Length", "" + file.length());
                response.setContentType("application/octet-stream;charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                outputStream = new BufferedOutputStream(response.getOutputStream());
                outputStream.write(FileUtils.readFileToByteArray(file));
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (outputStream != null) {
                        outputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    @ApiOperationSupport(order = 4)
    @ApiOperation("多文件上传")
    @PostMapping("/uploads")
    @ResponseBody
    public Resp<List<String>> ossUploads(MultipartFile[] file){
        List<String> fileList = Lists.newArrayList();
        for (MultipartFile f : file) {
            String uploadPath = doUpload(f);
            fileList.add(uploadPath);
        }
        return getRes(fileList);
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation("文件上传方式")
    @PostMapping("/get-upload-type")
    @ResponseBody
    public Resp<String> getUploadType() {
        return getRes(ossType);
    }


    @ApiOperationSupport(order = 3)
    @ApiOperation("单文件上传")
    @PostMapping(value = {"/upload", "upfile"})
    @ResponseBody
    public Resp<String> ossUpload(MultipartFile file) {
        String uploadPath = doUpload(file);
        return getRes(uploadPath);
    }


    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    private final String doUpload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = NFileUtils.getFileSuffix(fileName);
        try {
            String uploadPath = ossService.uploadSuffix(file.getInputStream(), suffix);
            return uploadPath;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
    }

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    private final String doFbUpload(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String suffix = NFileUtils.getFileSuffix(fileName);
        try {
            String uploadPath = ossService.fbUploadSuffix(file.getInputStream(), suffix);
            return uploadPath;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("文件上传失败");
        }
    }

    /**
     * 本地上传的文件跟路径
     *
     * @return
     */
    private final String getUploadDir() {
        return this.uploadDir;
    }
}
